

library(estimatr)
setwd("/Users/aspearot/Dropbox/MaLT 2017/Draft/submission_draft/ReStat/resubmission 2/replication package/malt/")

ps<-read.csv("Results/Predicted_Choices.csv",header=TRUE)
ps$ag_region<-NULL

ps$unit<-paste(ps$village,ps$ward,ps$district,ps$region,ps$ag_village,ps$ag_ward,ps$ag_district)

village_name<-as.character(tapply(ps$village_name,ps$unit,FUN=unique))
ward<-as.character(tapply(ps$ward,ps$unit,FUN=unique))
district<-as.character(tapply(ps$district,ps$unit,FUN=unique))
region<-as.character(tapply(ps$region,ps$unit,FUN=unique))
ag_village<-as.character(tapply(ps$ag_village,ps$unit,FUN=unique))
ag_ward<-as.character(tapply(ps$ag_ward,ps$unit,FUN=unique))
ag_district<-as.character(tapply(ps$ag_district,ps$unit,FUN=unique))
lam<-as.numeric(tapply(ps$lam,ps$unit,FUN=sum,na.rm=TRUE))
weighted_dist_std<-as.numeric(tapply(ps$weighted_dist_std,ps$unit,FUN=mean,na.rm=TRUE))

predict_shares<-data.frame(village_name,ward,district,ag_village,ag_ward,ag_district,lam,weighted_dist_std)


a<-read.csv("Data/buying_inputs_MNL_replication.csv",header=TRUE)

a$unit<-paste(a$village,a$ward,a$district,a$region,a$ag_village,a$ag_ward,a$ag_district)

village_name<-as.character(tapply(a$village,a$unit,FUN=unique))
ward<-as.character(tapply(a$ward,a$unit,FUN=unique))
district<-as.character(tapply(a$district,a$unit,FUN=unique))
region<-as.character(tapply(a$region,a$unit,FUN=unique))
ag_village<-as.character(tapply(a$ag_village,a$unit,FUN=unique))
ag_ward<-as.character(tapply(a$ag_ward,a$unit,FUN=unique))
ag_district<-as.character(tapply(a$ag_district,a$unit,FUN=unique))
shares<-as.numeric(tapply(a$select,a$unit,FUN=function(f){mean(f,na.rm=TRUE)}))
counts<-as.numeric(tapply(a$select,a$unit,FUN=function(f){sum(f,na.rm=TRUE)}))

actual_shares<-data.frame(village_name,ward,district,ag_village,ag_ward,ag_district,shares,counts)

nrow(actual_shares)
actual_shares<-merge(actual_shares,predict_shares)
nrow(actual_shares)

summary(glm(shares~log(lam),actual_shares,family = poisson(link="log")))




